package com.wyw.core.config.support;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.ehcache.Cache;

import org.apache.commons.lang.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.wyw.core.config.XmlConfigParse;
import com.wyw.core.config.dto.ColumnDto;
import com.wyw.core.config.dto.CommListDefineDto;
import com.wyw.core.exception.WYWException;
import com.wyw.core.secu.dto.XmlConfigType;
import com.wyw.core.util.CacheManager;

public class CommListDefineParse implements XmlConfigParse{

	@Override
	public void parse(XmlConfigType xmlConfigType, Document xmlConfig) throws Exception {
		// TODO Auto-generated method stub
		//System.out.println("xmlConfigType:"+xmlConfigType.getXmlConfigType());
		List<Element> commListDefineXmlList=xmlConfig.getRootElement().getChildren("listDefine");
		HashMap commListConfigMap = new HashMap();
		CommListDefineDto commListDefineDto;
		String id;
		for(Element commListDefineXml:commListDefineXmlList){
			id=commListDefineXml.getAttributeValue("id");
			if(commListConfigMap.containsKey(id)){
				throw new WYWException("id："+id+" 列表重复加载");
			}else{
				commListDefineDto  = new CommListDefineDto();
				commListDefineDto.setId(id);
				commListDefineDto.setDescription(commListDefineXml.getChildText("description"));
				parseColumnList(commListDefineDto,commListDefineXml.getChild("columns").getChildren("column"));
				commListConfigMap.put(id, commListDefineDto);
			}
		}
		
		net.sf.ehcache.Element processDefinitionMap=new  net.sf.ehcache.Element(CacheManager.comm_list_define_map,commListConfigMap);
		CacheManager.put(processDefinitionMap);
	}
	
	private void parseColumnList(CommListDefineDto commListDefineDto,List<Element> columnsList){
		List<ColumnDto> columns = new ArrayList();
		ColumnDto columnDto;
		for(Element column :columnsList){
			columnDto = new ColumnDto();
			columnDto.setId(column.getAttributeValue("id"));
			columnDto.setDesc(column.getChildText("desc"));
			columnDto.setAlign(column.getChildText("align"));
			columnDto.setWidth(new java.math.BigInteger(column.getChildText("width")).intValue());
			String exportable = column.getChildText("exportable");
			
			if(StringUtils.isNotEmpty(exportable)){
				columnDto.setExportable(new java.lang.Boolean(exportable));
			}
			
			String sortable = column.getChildText("sortable");
			if(StringUtils.isNotEmpty(sortable)){
				columnDto.setSortable(new java.lang.Boolean(sortable));
			}
			
			String hidden = column.getChildText("hidden");
			if(StringUtils.isNotEmpty(hidden)){
				columnDto.setHidden(new java.lang.Boolean(hidden));
			}
			
			columns.add(columnDto);
		}
		commListDefineDto.setColumns(columns);
	}

}
